***********************************************************************************
********"Macroprudential Regulation, Quantitative Easing, and Bank Lending"********
***********************************************************************************
* This file sets up a bank-province level dataset
***********************************************************************************
***********************************************************************************

*==================================================================================
**# Bookmark (input)
clear *
import sas ENTE_SEGN CENSITO_CRITTOG TIME DISBUR COM COMUNE_DIP using $inputdirectory/bloans, case(lower)
run RO_creditregister tm(2014m4) tm(2015m6) 0
keep bankid borrowerid time disbur comune_dip

merge m:1 bankid using $inputdirectory/INB_gru2015, keepus(gru)
keep if _merge!=2
drop _merge
replace gru=bankid if gru==.
drop bankid
rename gru bankid

merge m:1 comune_dip using $inputdirectory/INB_comprov2015, keepus(prov)
keep if _merge!=2
drop _merge

collapse (sum) disbur, by(bankid borrowerid time prov)
duplicates tag bankid borrowerid time, g(dup)

egen xxx=max(disbur), by(bankid borrowerid time)
gen yyy=prov if disbur==xxx
egen zzz=max(yyy), by(bankid borrowerid time)
replace prov=zzz if dup>0
drop xxx yyy zzz
collapse (sum) disbur, by(bankid borrowerid time prov)

egen id=group(bankid borrowerid)
xtset id time

gen new=0
replace new=1 if L.id==.&L2.id==.&L3.id==.
gen old=1-new
gen disburold=disbur*old
drop old new 
keep if time>=tm(2014m6)&time<=tm(2015m6)

* Collapse by by bank-province
collapse (sum) disbur disburold, by(bankid time prov)

merge m:1 bankid using $inputdirectory/INB_preann2014m12, keepus(dtop85e13 exlnassets excashas)
keep if _merge==3
drop _merge

merge m:1 bankid time using $inputdirectory/INB_refinm2015, keepus(lncrefin)
keep if _merge!=2
drop _merge

* Compute some province (and bank-province) indicators
egen totdisburcom=sum(disbur), by(time prov)

gen ttt=disbur
replace ttt=0 if dtop85e13==0
egen totdistr85=sum(ttt), by(time prov)
egen zzz85=sum(ttt), by(time prov bankid)
drop ttt

gen sharedis85=100*(totdistr85)/(totdisburcom)
gen sharedis85R=100*(totdistr85-zzz85)/(totdisburcom-disbur)
replace sharedis85R=sharedis85 if sharedis85R==.

foreach x of var sharedis85 {
gen xxx=`x' if time==tm(2014m12)
drop `x'
egen `x'=max(xxx), by(prov)
drop xxx
}

foreach x of var sharedis85R {
gen xxx=`x' if time==tm(2014m12)
drop `x'
egen `x'=max(xxx), by(prov bankid)
drop xxx
}
gen interdis85=sharedis85*dtop85e13
gen interdisno85=sharedis85*(1-dtop85e13)
gen interdis85R=sharedis85R*dtop85e13
gen interdisno85R=sharedis85R*(1-dtop85e13)

* LINE ADDED (NOT NEEDED WITH THE ORIGINAL DATASETS)
drop if prov==.
egen id=group(bankid prov)
xtset id time

**# Bookmark (saving dataset - bank-province dataset)
compress
save $inputdirectory/INB_provbank2015, replace
